package com.quanshi.shopping_order_service.service;


import cn.hutool.core.util.IdUtil;
import com.quanshi.shopping_common.entity.CartGoods;
import com.quanshi.shopping_common.entity.Orders;
import com.quanshi.shopping_common.enums.OrderStatusEnum;
import com.quanshi.shopping_common.service.IOrderService;
import com.quanshi.shopping_order_service.mapper.CartGoodsMapper;
import com.quanshi.shopping_order_service.mapper.OrdersMapper;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@DubboService
@Transactional //本地事务注解
public class OrderServiceImpl implements IOrderService {

    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private CartGoodsMapper cartGoodsMapper;

    @Override
    public Orders add(Orders orders) {
        //设置订单（雪花算法）
        String orderId = IdUtil.getSnowflakeNextIdStr();
        orders.setId(orderId);
        //设置订单时间
        orders.setCreateTime(LocalDateTime.now());
        //设置订单状态
        orders.setStatus(OrderStatusEnum.UNPAID.getCode());

        //新增订单
        ordersMapper.insert(orders);

        //新增订单明细（订单商品）
        List<CartGoods> cartGoodsList = orders.getCartGoods();
        for (CartGoods cartGoods : cartGoodsList) {
            //设置订单商品的订单id
            cartGoods.setOrderId(orderId);

            //新增订单明细
            cartGoodsMapper.insert(cartGoods);
        }

        //TODO  删除购物车（redis中）已经下单的商品


        return orders;
    }

    @Override
    public void update(Orders orders) {
        ordersMapper.updateById(orders);
    }

    @Override
    public Orders findById(String id) {

        Orders orders = ordersMapper.findById(id);

        return orders;
    }

    @Override
    public List<Orders> findUserOrders(Long userId, String status) {

        List<Orders> ordersList = ordersMapper.findUserOrders(userId,status);

        return ordersList;
    }
}
